<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPermissionAnchorModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use Illuminate\Console\Command;

class RestoreOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:restore-order {orderNo} {shopId?}';

    /**
     * The console command description.
     *
     * php artisan openShop:restore-order KD2022042781647939 13307
     *
     * @var string
     */
    protected $description = '还原订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $orderNo = $this->argument('orderNo');
        if (!$orderNo) {
            dd('orderNo不能为空');
        }

        $shopId = $this->argument('shopId');

        $signOrder = OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->first();
        if (!$signOrder) {
            dd('找不到订单');
        }

        if ($signOrder->status == SignOrderEnum::ORDER_STATUS_OK) {
            $this->info('订单已还原，继续往下执行...');
        }

        OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->update(
            [
                'status' => SignOrderEnum::ORDER_STATUS_OK,
                'dissolveStatus' => 0
            ]);

        OpenShopSiteMissionModel::query()->withoutGlobalScope('isDel')->where('orderNo', $orderNo)->update(['isDeleted' => 0]);
        OpenShopSiteLocationModel::query()->withoutGlobalScope('isDel')->where('orderNo', $orderNo)->update(['isDeleted' => 0]);
        OpenShopSignOrderPermissionAnchorModel::query()->where('orderNo', $orderNo)
                                              ->update(['orderStatus' => SignOrderEnum::ORDER_STATUS_OK]);

//        OpenShopUserContractModel::query()->where('');
        if ($shopId) {
            OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->update(['shopId' => $shopId]);
        }

        $this->info($orderNo . '订单已恢复');
    }
}
